package responses

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-playground/validator/v10"
	"todo-list/config"
	"todo-list/constants"
	"todo-list/types"
	"todo-list/utils/e"
)

// RespList 构建分页类型的返回值
func RespList(items any, total int64) types.Response {
	return types.Response{
		Status: constants.CodeSuccess,
		Data: types.PagedData{
			Item:  items,
			Total: total,
		},
		Msg: config.TranslateMsg(constants.CodeSuccess.GetMsg()),
	}
}

// RespSuccess 构建普通的操作成功的响应
func RespSuccess() types.Response {
	return types.Response{
		Status: constants.CodeSuccess,
		Msg:    config.TranslateMsg(constants.CodeSuccess.GetMsg()),
	}
}

// RespSuccessWithData 构建带有返回值的操作成功的响应
func RespSuccessWithData(data any) types.Response {
	return types.Response{
		Status: constants.CodeSuccess,
		Data:   data,
		Msg:    config.TranslateMsg(constants.CodeSuccess.GetMsg()),
	}
}

// RespError 构建错误的响应
func RespError(err error, code constants.StatusCode) types.Response {
	var ve validator.ValidationErrors
	if errors.As(err, &ve) {
		for _, filedError := range ve {
			filed := config.TranslateField(filedError.Field())
			tag := config.TranslateTag(filedError.Tag())
			return RespErrorWithMsg(err, constants.CodeInvalidParams, fmt.Sprintf("%s%s", filed, tag))
		}
	}
	var unmarshalTypeError *json.UnmarshalTypeError
	if errors.As(err, &unmarshalTypeError) {
		code = constants.CodeJsonUnmarshalType
	}
	return RespErrorWithMsg(err, code, config.TranslateMsg(code.GetMsg()))
}

// RespErrorWithMsg 构建自定义消息的错误响应
func RespErrorWithMsg(err error, code constants.StatusCode, msg string) types.Response {
	if err == nil {
		err = e.New(msg)
	}
	return types.Response{
		Status: code,
		Msg:    msg,
		Error:  err.Error(),
	}
}
